<template>
  <div class="section-container">
    <div class="section-title">
      登录页设置
    </div>
    <div class="section-actions">
      <div class="actions left">
        <el-button type="primary" @click="handleAdd">添加登录页</el-button>
      </div>
    </div>
    <div class="table-box">
      <RuifoxTable :default-index="true" :default-checkbox="false" v-model:tableData="tableData"
        v-model:fieldList="fieldList">
        <template #mode="{ element }">
          {{ element.mode === 1 ? '简约模式' : '标准模式' }}
        </template>
        <template #updateTime="{ element }">
          {{ element.updateTime ? dayjs(element.updateTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </template>
        <template #options="{ element }">
          <div class="table-td-option">
            <el-button type="primary" link @click="handleDelete(element)">删除</el-button>
            <el-button type="primary" link @click="handleEdit(element)">编辑</el-button>
            <el-button type="primary" link @click="handlePreview(element)">预览</el-button>
          </div>
        </template>
      </RuifoxTable>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加登录页' : '编辑登录页'"
      destroy-on-close
      fullscreen
      :close-on-press-escape="false"
    >
      <div class="edit-container">
        <el-scrollbar class="edit-form">
          <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
            <el-form-item label="系统名称" prop="name">
              <el-button type="primary" link @click="handleRichText('name')">在富文本中编辑</el-button>
            </el-form-item>
            <el-form-item label="Key" prop="title">
              <el-input v-model="formData.title" placeholder="请输入系统key" />
            </el-form-item>
            <el-form-item label="模式" prop="mode">
              <el-select v-model="formData.mode" placeholder="请选择模式">
                <el-option label="简约模式" :value="1" />
                <el-option label="标准模式" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="扫码登录" prop="useQrCode">
              <el-switch v-model="formData.useQrCode" />
            </el-form-item>
            <el-form-item label="Logo">
              <div class="swiper-list">
                <div class="swiper-draggable-list" @click="handleAddImage('logo')">
                  <div v-if="formData.logo" class="swiper-item" @mouseover="logoMaskShow = true" @mouseleave="logoMaskShow = false">
                    <img :src="formData.logo" />
                    <div v-show="logoMaskShow" class="format-box-mask">
                      <el-button-group>
                        <el-button size="small" :icon="Delete" @click.stop="handleDeleteImage('logo')" />
                      </el-button-group>
                    </div>
                  </div>
                  <div v-else class="swiper-item">
                    <el-icon :size="24">
                      <Plus />
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="背景图片">
              <div class="swiper-list">
                <draggable v-model="formData.backgrounds" :animation="150" item-key="id" handle=".swiper-item"
                  class="swiper-draggable-list">
                  <template #item="{ element, index }">
                    <div class="swiper-item" @mouseenter="activeIndex = index" @mouseleave="activeIndex = null">
                      <img :src="element" />
                      <div class="format-box-mask" v-show="activeIndex === index">
                        <el-button-group>
                          <el-button size="small" :icon="Delete" @click="handleDeleteImage('backgrounds', index)" />
                        </el-button-group>
                      </div>
                    </div>
                  </template>
                </draggable>
                <div class="swiper-item" @click="handleAddImage('backgrounds')">
                  <el-icon :size="24">
                    <Plus />
                  </el-icon>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="背景轮播间隔" prop="delay">
              <el-input-number v-model="formData.delay" :min="0" :max="10" :step="0.5" />
              <span class="unit">秒</span>
            </el-form-item>
            <el-form-item label="版权信息" prop="copyright">
              <el-button type="primary" link @click="handleRichText('copyright')">在富文本中编辑</el-button>
            </el-form-item>
            <el-form-item label="系统介绍" prop="description">
              <el-button type="primary" link @click="handleRichText('description')">在富文本中编辑</el-button>
            </el-form-item>
            <el-form-item label="额外按钮">
              <div v-for="(btn, index) in formData.extraButtons" :key="index" class="extra-button-item">
                <el-input v-model="btn.text" placeholder="按钮文字" />
                <el-input v-model="btn.url" placeholder="跳转链接" />
                <el-button type="danger" link @click="removeExtraButton(index)">删除</el-button>
              </div>
              <el-button type="primary" link @click="addExtraButton">添加按钮</el-button>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <div class="preview-section">
          <Preview :setting="formData" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <FilesUpload v-model:showDialog="showImageUpload" :limit="1" @getFileList="handleGetImg" />
    <el-dialog v-model="richTextDialog" destroy-on-close title="富文本编辑" width="1000px">
      <TinymceEditor v-model:modelValue="richText" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="richTextDialog = false">取消</el-button>
          <el-button type="primary" @click="handleRichTextConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <Preview v-if="previewShow" :setting="curSetting" :isFullscreen="true" @close="previewShow = false" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { insertSetting, updateSetting, deleteSetting, selectSettingList } from '@/api/setting'
import { ElMessage, ElMessageBox } from 'element-plus'
import Preview from './components/Preview.vue'
import dayjs from 'dayjs'
import draggable from 'vuedraggable'
// import { nextTick } from 'vue'

// 表格字段配置
const fieldList = ref([
  {
    title: 'Key',
    name: 'title',
    width: 120
  },
  {
    title: '名称',
    name: 'nameText'
  },
  {
    title: '模式',
    name: 'mode'
  },
  {
    title: '更新时间',
    name: 'updateTime'
  },
  {
    title: '操作',
    name: 'options',
    fixed: 'right',
    width: 160
  }
])
const getText = (data) => {
  const tempElement = document.createElement('div')
  tempElement.innerHTML = data
  return tempElement.textContent || tempElement.innerText
}

const tableData = ref([])
const _getSettingList = async () => {
  const res = await selectSettingList()
  if (res.code === 20000) {
    tableData.value = res.data
    tableData.value.forEach(item => {
      item.nameText = getText(item.name)
    })
  }
}
_getSettingList()

const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const defaultFormData = {
  name: '',
  mode: 'simple',
  title: '',
  copyright: '',
  logo: '',
  description: '',
  backgrounds: [],
  delay: 3,
  extraButtons: []
}
const formData = ref({ ...defaultFormData })
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入Key', trigger: 'blur' }],
  mode: [{ required: true, message: '请选择模式', trigger: 'change' }]
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = { ...defaultFormData }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (data) => {
  ElMessageBox.confirm('确认删除该登录页配置吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    const res = await deleteSetting({id: data.id})
    if (res.code === 20000) {
      ElMessage.success('删除成功')
      _getSettingList()
    }
  })
}

// 图片上传
const showImageUpload = ref(false)
const imageField  = ref('')
const logoMaskShow = ref(false)
const handleAddImage = async (data) => {
  imageField.value = data
  logoMaskShow.value = false
  showImageUpload.value = true
}

const handleGetImg = (data) => {
  if (imageField.value === 'logo') {
    formData.value.logo = data[0].url
  } else if (imageField.value === 'backgrounds') {
    formData.value.backgrounds.push(data[0].url)
  }
}

const activeIndex = ref(null)
const handleDeleteImage = (type, index) => {
  if (type === 'backgrounds') {
    formData.value.backgrounds.splice(index, 1)
  } else {
    formData.value.logo = ''
  }
}

// 添加额外按钮
const addExtraButton = () => {
  formData.value.extraButtons.push({ text: '', url: '' })
}

// 删除额外按钮
const removeExtraButton = (index) => {
  formData.value.extraButtons.splice(index, 1)
}

// 富文本编辑
const richTextDialog = ref(false)
const richText = ref('')
const richTextField  = ref('')
const handleRichText = (data) => {
  richTextField.value = data
  richText.value = formData.value[data]
  richTextDialog.value = true
}

const handleRichTextConfirm = () => {
  formData.value[richTextField.value] = richText.value
  richTextDialog.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = formData.value.id ? await updateSetting(formData.value) : await insertSetting(formData.value)
      if (res.code === 20000) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        _getSettingList()
      }
    }
  })
}

// 预览
const previewShow = ref(false)
const curSetting = ref(null)
const handlePreview = (data) => {
  curSetting.value = data
  previewShow.value = true
}
</script>

<style scoped lang="scss">
.edit-container {
  display: flex;
  height: calc(100vh - 180px);

  .edit-form {
    flex: 0 0 400px;
    overflow-y: auto;
    padding: 0 20px;
    background-color: #fff;
    border-right: 1px solid #e4e7ed;

    .swiper-list {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-gap: 10px;
      width: calc(100% - 2px);

      .swiper-draggable-list {
        display: contents; // 这会保持网格布局
      }

    }

    .swiper-item {
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      margin-top: 10px;
      width: 100%;
      height: 70px;
      border: 1px solid #f2f2f2;
      overflow: hidden;
      cursor: pointer;

      img {
        width: 100%;
        height: 70px;
        object-fit: contain;
      }

      .format-box-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        transition: opacity 0.3s ease;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgba($color: #000000, $alpha: 0.2);
      }

      &:hover {
        border: 1px solid $mainColor;
      }
    }
  }

  .preview-section {
    flex: 1;
    overflow: hidden;
  }
}

.extra-button-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.unit {
  margin-left: 10px;
  color: #666;
}
</style>
